<template>
  <a-card class="task-tabs-card">
    <template #title>
      <div v-if="TaskStatusEnum.draft === taskInfo.taskStatus && !disabled" class="flex items-center justify-between">
        <div style="line-height: 32px">
          是否需要报表：
          <a-radio-group v-model:value="isNeedReport" @change="isNeedReportChange">
            <a-radio :value="true">需要</a-radio>
            <a-radio :value="false">不需要</a-radio>
          </a-radio-group>
        </div>
        <a-button v-if="isNeedReport" type="primary" @click="chooseReportTem">选择报表</a-button>
      </div>
    </template>
    <TnNewTable v-if="isNeedReport" :query-data="null" :tn-table-props="tnTableProps" :columns="columns">
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'templateFileName'">
          <div class="flex items-center justify-between w-full">
            <div class="color-primary text-ellipsis grow-1">{{ record.templateFileName }}</div>
            <div class="whitespace-nowrap">
              <a-button type="link" @click="downloadOrPreviewFile(1, record)">预览</a-button>
              <a-button
                v-if="TaskStatusEnum.draft === taskInfo.taskStatus && !disabled"
                v-docCanEdit
                type="link"
                @click="editFile(record)"
                >在线编辑</a-button
              >
              <a-button type="link" @click="downloadOrPreviewFile(2, record)">下载</a-button>
            </div>
          </div>
        </template>
        <template v-if="column.dataIndex === 'archiveFolderPath'">
          {{ record.archiveFolderPath || record.archiveFolderName }}
        </template>
        <template v-if="column.dataIndex === 'edit' && !disabled">
          <template v-if="TaskStatusEnum.draft === taskInfo.taskStatus">
            <a-button type="link" @click="editHandle(record)">编辑</a-button>
            <a-popconfirm
              title="是否确认删除?"
              ok-text="确认"
              cancel-text="取消"
              :get-popup-container="(triggerNode):any => triggerNode.parentNode"
              @cancel="() => {}"
              @confirm="delHandle(record.receiptId)"
            >
              <a-button type="link" danger>删除</a-button>
            </a-popconfirm>
          </template>
        </template>
      </template>
    </TnNewTable>
    <IcpEmpty v-else />
  </a-card>

  <selectReportTemplate ref="refSelectReportTemplate" @submit="submitSelect"></selectReportTemplate>
  <add
    ref="refAdd"
    :task-id="taskInfo.taskId"
    :is-need-select-folder="isNeedSelectFolder"
    :speed-id="taskInfo.speedId"
    :update-fn="taskInfo.updateReportListApi"
    :add-fn="taskInfo.addReportListApi"
    :is-input-folder="isInputFolder"
    :is-temp="taskInfo.sourceType !== 'project'"
    @reload="reloadTable"
  ></add>
  <spire-cloud-editor ref="refSpireCloudEditor" @file-change="fileChange" />
</template>
<script setup lang="ts">
import { ref, computed } from 'vue'
import selectReportTemplate from './components/selectReportTemplate.vue'
import add from './components/addReport.vue'
import { getProjectReport, delProjectReport } from '@@/api/report/index'
import { reportColumnsList, reportConfigColumnsList } from './index'
import { TaskStatusEnum } from '@@/enums/taskEnum'
import { getAppEnvConfig } from '@/utils/env'
import { UploadAndPreview } from '@@/components/uploadAndPreview/index'

const { VITE_GLOB_API_URL, VITE_GLOB_PRIVIEW_FILE_URL } = getAppEnvConfig()
const useUploadAndPreview = new UploadAndPreview(VITE_GLOB_API_URL)

const emits = defineEmits(['resetData'])

const props = defineProps<{
  taskInfo: any
  needReport: boolean | undefined
  disabled?: boolean
  isNeedSelectFolder?: boolean
  isInputFolder?: boolean
  source?: string
}>()
const isNeedReport = ref(props.needReport ? true : false)
const columns = computed(() => {
  if (props.taskInfo.sourceType === 'project') {
    return reportColumnsList
  }
  return reportConfigColumnsList
})
const isNeedReportChange = () => {
  const taskId = props.taskInfo.mainId || 'taskId'
  const required = props.taskInfo.isPerNeedReport || 'required'
  props.taskInfo
    .updateReportRequiredApi({
      [taskId]: props.taskInfo.taskId,
      [required]: isNeedReport.value
    })
    .then(() => {
      emits('resetData', isNeedReport.value)
    })
    .catch(() => {
      isNeedReport.value = props.needReport || false
    })
}
const refSelectReportTemplate = ref()
const chooseReportTem = () => {
  refSelectReportTemplate.value.show()
}
const refAdd = ref()
const submitSelect = (type, data) => {
  refAdd.value.show(type, data)
}
const tableData = ref()
const reloadTable = () => {
  let archiveFolderType
  if (props.source === 'finance') {
    // finance 不传该字段
    archiveFolderType = null
  } else if (props.taskInfo.sourceType === 'progressTemplate') {
    archiveFolderType = 1
  } else if (props.taskInfo.sourceType === 'project') {
    archiveFolderType = 2
  } else {
    archiveFolderType = null
  }
  getProjectReport({
    businessId: props.taskInfo.taskId,
    archiveFolderType
  }).then((res) => {
    tableData.value = res || []
    tnTableProps.value.tableData = tableData.value
  })
}
reloadTable()
const delHandle = (id) => {
  delProjectReport({
    id
  }).then(() => {
    reloadTable()
  })
}
const editHandle = (item) => {
  refAdd.value.show(3, item)
}
/**
 * 在线编辑
 */
const refSpireCloudEditor = ref()
const editFileRecord = ref()
const editFile = (record) => {
  const timestamp = new Date().getTime()
  editFileRecord.value = record
  const fileUrl = `${VITE_GLOB_PRIVIEW_FILE_URL}/Rest/doc/file/filePreview?timestamp=${timestamp}&docId=${record.templateFileId}&addWatermarkFlag=false&filename=${record.templateFileName}`
  refSpireCloudEditor.value.show({
    modalOperateType: 'edit',
    originalFileId: record.templateFileId,
    sourceUrl: fileUrl,
    fileName: record.templateFileName,
    openReviewChanges: false,
    canEdit: true
  })
}
const fileChange = (_type, file) => {
  props.taskInfo
    .updateReportListApi({
      ...editFileRecord.value,
      templateFileId: file.fileId,
      templateFileName: file.name
    })
    .then(() => {
      reloadTable()
    })
}
/**
 * 在线编辑 end
 */

/**
 * 预览和下载处理,type:1 预览 ，2 下载
 */
const downloadOrPreviewFile = (type, record) => {
  let fileId,
    fileName,
    addWatermarkFlag = false
  // 草稿、已发布、待反馈的时候预览和下载原文件
  if (
    [TaskStatusEnum.draft, TaskStatusEnum.pendingSubmission, TaskStatusEnum.pendingFeedback].includes(
      props.taskInfo.taskStatus
    )
  ) {
    fileId = record.templateFileId
    fileName = record.templateFileName
  } else {
    fileId = record.receiptFileId
    fileName = record.receiptFileName
  }
  // 已完成的，下载需要带水印
  if (TaskStatusEnum.completed === props.taskInfo.taskStatus) {
    addWatermarkFlag = true
  }
  if (type === 1) {
    useUploadAndPreview.previewFile(fileId, fileName)
  } else {
    useUploadAndPreview.downloadFileApi2({
      fileId,
      fileName,
      addWatermarkFlag
    })
  }
}
const tnTableProps = ref({
  name: 'TaskKanbanReportConfigTable',
  tableData: tableData.value,
  showNo: false,
  needPagination: false,
  needToolbar: false
})
</script>
